import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { message } from 'ant-design-vue'

export interface CartItem {
  id: number
  title: string
  description: string
  cover: string
  price: number
  quantity: number
}

export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const cartItems = ref<CartItem[]>([])

  // 计算属性
  const cartCount = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
  })

  const cartTotal = computed(() => {
    return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
  })

  // 添加商品到购物车
  const addToCart = (product: any) => {
    const existingItem = cartItems.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += 1
      message.success('商品数量已增加')
    } else {
      cartItems.value.push({
        id: product.id,
        title: product.title,
        description: product.description,
        cover: product.cover,
        price: product.price,
        quantity: 1
        
      })
      message.success('已添加到购物车')
    }
  }

  // 从购物车移除商品
  const removeFromCart = (productId: number) => {
    const index = cartItems.value.findIndex(item => item.id === productId)
    if (index !== -1) {
      cartItems.value.splice(index, 1)
      message.success('已从购物车移除')
    }
  }

  // 更新商品数量
  const updateQuantity = (productId: number, quantity: number) => {
    const item = cartItems.value.find(item => item.id === productId)
    if (item) {
      if (quantity <= 0) {
        removeFromCart(productId)
      } else {
        item.quantity = quantity
      }
    }
  }

  // 清空购物车
  const clearCart = () => {
    cartItems.value = []
    message.success('购物车已清空')
  }

  // 结算
  const checkout = () => {
    if (cartItems.value.length === 0) {
      message.warning('购物车是空的')
      return false
    }
    
    // 这里可以调用结算API
    message.success('结算成功！')
    clearCart()
    return true
  }

  return {
    cartItems,
    cartCount,
    cartTotal,
    addToCart,
    removeFromCart,
    updateQuantity,
    clearCart,
    checkout
  }
})

